# coding: utf-8

import re
import ast
import time

from django import template
from jd_oss.tools import *
from jd_user.tools import *
from django.contrib.auth.models import User

register = template.Library()


@register.filter(name='get_role')
def get_role(is_superuser):
    if is_superuser:
        return u"超级管理员"
    else:
        return u"普通用户"

@register.filter(name='get_list_value')
def get_list_value(list, index):
    """ 返回对象的属性值 """
    return list[index]

@register.filter(name='get_dict_value')
def get_dict_value(dict, key):
    """ 返回字典的指定值 """
    values = dict[key]
    return " ".join(values) if len(values) == 1 else values


@register.filter(name='get_obj_value')
def get_obj_value(obj, key):
    """ 返回对象的属性值 """
    return getattr(obj, key)


@register.filter(name='to_zh_department')
def to_zh_department(username):
    """ 返回用户所在部门的中文表示  """
    ldep = UserTools.get_user_dep(username)
    return ','.join(ldep.values())

@register.filter(name='to_zh_group')
def to_zh_group(username):
    """ 返回用户所在用户组的中文标示  """
    lgrp = UserTools.get_user_group(username)
    return ','.join(lgrp.values())


@register.filter(name='to_zh_username')
def to_zh_username(username):
    """ 转换成ldap上的中文名称 """
    luser = UserTools.get_user(username)[0]
    if luser:
        return ''.join(luser.attrs.get('displayName', "无名氏"))
    return ''


@register.filter(name='int2str')
def int2str(value):
    """
    int 转换为 str
    """
    return str(value)


@register.filter(name='bool2str')
def bool2str(value):
    if value:
        return u'是'
    else:
        return u'否'


@register.filter(name='result2bool')
def result2bool(result=''):
    """将结果定向为结果"""
    result = eval(result)
    unreachable = result.get('unreachable', [])
    failures = result.get('failures', [])

    if unreachable or failures:
        return '<b style="color: red">失败</b>'
    else:
        return '<b style="color: green">成功</b>'


@register.filter(name='str_to_list')
def str_to_list(info):
    """
    str to list
    """
    print ast.literal_eval(info), type(ast.literal_eval(info))
    return ast.literal_eval(info)
